//
//  FixDeviceViewController.m
//  sensen_ios
//
//  Created by hebidu on 2016/9/21.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "FixDeviceVC.h"
#import "APIs.h"
@interface FixDeviceVC ()

@property(nonatomic,strong) UILabel * lblProgress ;
@property(nonatomic,strong) UIButton * btnCtrl ;
//@property(nonatomic,strong) UITextField * tfSessionId ;

@end

@implementation FixDeviceVC

-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.view setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
    
}

-(void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initViews];
    [self autolayoutConstraints];
    [self addListener];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) initViews{
    
    self.title = @"设备修复工具(Beta版)";
    
//    _tfSessionId = [[UITextField alloc] init];
//    _tfSessionId.text = @"50";
//    
//    [self.view addSubview:_tfSessionId];
    
    _lblProgress = [[UILabel alloc] init];
    _lblProgress.text = [NSString stringWithFormat:@"修复进度: %.2f",0.0f];
    //    _lblProgress.backgroundColor = [UIColor redColor];
    _lblProgress.textColor = [UIColor redColor];
    _lblProgress.translatesAutoresizingMaskIntoConstraints = NO;
    _lblProgress.textAlignment = NSTextAlignmentCenter;
    
    [self.view addSubview:_lblProgress];
    
    _btnCtrl = [[UIButton alloc] init];
    [_btnCtrl setBackgroundColor:[UIColor blueColor]];
    [_btnCtrl setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _btnCtrl.translatesAutoresizingMaskIntoConstraints = NO;
    
    [_btnCtrl setTitle:@"开始修复" forState:UIControlStateNormal];
    
    [self.view addSubview:_btnCtrl];
    
}

-(void) addListener{
    [_btnCtrl addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
}

-(void) btnClick:(id) sender{
//    [self getNowSessionId];
    _lastSessionId = 0;
    [self start];
}


-(void) getNowSessionId{
    
    
    __block FixDeviceVC * that = self;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        
        [[APIs sharedInstance] connectWithUid: that.did
                              lanSearchEnable:YES
                                      success:^(NSInteger session){
                                          
                                          NSLog(@"Connect success with session %ld", (long)session);
                                          
                                          that.lastSessionId = (INT32) session;
                                          [that start];
                                          
                                          
                                      } failure:^(NSInteger errorCode) {
                                          NSString * errMsg = [DeviceCtrl getPPPPConnectErrMsg:errorCode];
                                          
                                          dispatch_queue_t mainQueue = dispatch_get_main_queue();
                                          dispatch_async(mainQueue, ^{
                                              
                                              [SVProgressHUD dismiss];
                                              [[[UIAlertView alloc] initWithTitle:@"❌修复失败，请重试"
                                                                          message:[NSString stringWithFormat:@"错误信息：%@", errMsg]
                                                                         delegate:nil
                                                                cancelButtonTitle:@"确定"
                                                                otherButtonTitles:nil, nil] show];
                                              
                                          });
                                      }];
        
        
        
    });//END Connect
    
}


- (void) autolayoutConstraints{
    
    
    NSDictionary *dict = NSDictionaryOfVariableBindings(_lblProgress,_btnCtrl);
        
    NSString * vfCenter = @"V:|-20-[_lblProgress(==64)]|";//垂直，距离父级视图10单位
    NSString * hfCenter = @"H:|-10-[_lblProgress]-10-|";
    
    NSString * btnVFCenter = @"V:[_lblProgress]-20-[_btnCtrl(==64)]";
    NSString * btnHFCenter = @"H:|-10-[_btnCtrl]-10-|";
    
//    NSString * tfVf = @"V:[_btnCtrl]-20-[_tfSessionId(==64)]";
//    NSString * tfHf = @"H:|-10-[_tfSessionId]-10-|";
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:vfCenter options:0 metrics:nil views:dict]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:hfCenter options:0 metrics:nil views:dict]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:btnVFCenter options:0 metrics:nil views:dict]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:btnHFCenter options:0 metrics:nil views:dict]];
    
    
//    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:tfVf options:0 metrics:nil views:dict]];
//    
//    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:tfHf options:0 metrics:nil views:dict]];
    

}

-(void) fixing{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [_btnCtrl setTitle:@"正在修复中..." forState:UIControlStateDisabled];
        
        _btnCtrl.enabled = NO;
        [_btnCtrl setBackgroundColor:[UIColor lightGrayColor]];
        
    });
}
-(void) fixDone{
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        _btnCtrl.enabled = YES;
        [_btnCtrl setBackgroundColor:[UIColor blueColor]];
    });
}

-(void) start{
    
    if(_btnCtrl.enabled == NO){
        return ;
    }
    
    
    int startSessionId = _lastSessionId;
    
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self fixing];
        int sessionId = startSessionId;
        int sessionEndId = startSessionId + 20000;
        
        
        for (; sessionId <= sessionEndId; sessionId ++ ) {
            [[APIs sharedInstance] close:sessionId];
        
            [self updateProgress:sessionId :sessionEndId];
            if(sessionId % 1000 == 0){
                [NSThread sleepForTimeInterval:1];
            }
        }
        
        [self fixDone];
    });
    
}

-(void) updateProgress:(int) current :(int) total{
    
    double percent = current / (double) total;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        _lblProgress.text = [NSString stringWithFormat:@"修复进度: %.2f %@", percent*100, @"%"];
    });
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
